/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 * Description: 性能评估器相关源文件
 * Author: qingjicheng
 * Create: 2022-8-1
 */

#include "connected_graph.h"
#include <memory>
#include "evaluator_log_def.h"

namespace HcclEvaluator {
constexpr u32 MAX_TOPO_LEVEL = 5;

ConnectedGraph::ConnectedGraph() : adjaMatrixes_(MAX_TOPO_LEVEL)
{
}

ConnectedGraph::~ConnectedGraph()
{
}

HcclResult ConnectedGraph::SetSubgraphAdjaMutrix(AdjacencyMatrix<> &&matrix, u32 level)
{
    if (level >= MAX_TOPO_LEVEL) {
        EVALUATOR_ERROR("push subgraph err, level[%u]\n", level);
        return HCCL_E_PARA;
    }

    adjaMatrixes_[level] = std::forward<AdjacencyMatrix<> &&>(matrix);

    if (level > maxLevel_) {
        maxLevel_ = level;
    }
    return HCCL_SUCCESS;
}

HcclResult ConnectedGraph::ParseAllSubgraphs()
{
    TimePoint start = TimeNow();
    for (u32 i = 0; i <= maxLevel_; i++) {
        std::vector<std::unique_ptr<ConnectedSubgraph>> subgraphs;
        EVALUATOR_CHK_RET(subgraphFactory_.CreateSubgraphs(adjaMatrixes_[i], subgraphs));

        EVALUATOR_CHK_RET(CheckSubgraphs(subgraphs));
        subgraphNodeSize_.push_back(subgraphs[0]->GetNodeSize());
        multiLayerSubgraphs_.push_back(std::move(subgraphs));
    }
    EVALUATOR_INFO("ParseAllSubgraphs duration = %lld us\n", DurationUs(TimeNow() - start));
    return HCCL_SUCCESS;
}

HcclResult ConnectedGraph::CheckSubgraphs(std::vector<std::unique_ptr<ConnectedSubgraph>> &subgraphs)
{
    if (subgraphs.size() == 0) {
        EVALUATOR_ERROR("subgraphs size is zero\n");
        return HCCL_E_PARA;
    }
    u32 nodeSize = subgraphs[0]->GetNodeSize();
    for (auto &subgraph : subgraphs) {
        if (subgraph->GetNodeSize() != nodeSize) {
            EVALUATOR_ERROR("node size[%u] is diff with subgraph 0's node size[%u]\n", subgraph->GetNodeSize(),
                nodeSize);
            return HCCL_E_NOT_SUPPORT;
        }
    }
    return HCCL_SUCCESS;
}
} // namespace HcclEvaluator